package com.hanbang.taitaigou.ui.activity.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.BannerAdData;
import com.hanbang.taitaigou.model.BaoKuanData;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.gouwuche.GouWuCheActivity;
import com.hanbang.taitaigou.ui.activity.taitaigou.ProductDetailsActivity;
import com.hanbang.taitaigou.ui.adapter.BannerAdAdapter;
import com.hanbang.taitaigou.ui.widget.CircleTextView;
import com.hanbang.taitaigou.ui.widget.GridViewForScrollView;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.http.PagingHelp;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanxin on 2016/5/23.
 */
public class TeChanActivity extends BaseActivity {
    private SwipeRefreshLayout id_swipe_ly_right;
    private GridViewForScrollView goodgrid;
    private PagingHelp pagingHelp = new PagingHelp(this);
    private List<BaoKuanData> list = new ArrayList<>();
    private BaoKuanAdapter baoKuanAdapter;
    private CircleTextView circleTextView;
    private LinearLayout ll_jinrugwc;

    private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<>();
    private BannerAdAdapter bannerAdAdapter = null;
    private ScrollView sv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baokuan);
        initView();
        setOnClickListener();
        getGoodByType(true);
        shuaxin();
        getBannerImage();

        IntentFilter intentFilter = new IntentFilter(GwcDbUtil.GWC_CHANG_CLEAR);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_ADD);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_SUB);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG);
        intentFilter.addAction(GwcDbUtil.DELETE_DB);
        registerReceiver(broadcastReceiver, intentFilter);

    }

    /**
     * 获取广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_ADD)) {
                upDataNumberAdd();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_SUB)) {
                upDataNumberSub();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG)) {
                upDataNumber();
            } else if (TextUtils.equals(action, GwcDbUtil.GWC_CHANG_CLEAR)) {
                upDataNumber(0);
            }
        }
    };

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {
        goodgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startXQ(TeChanActivity.this, String.valueOf(list.get(position).getNumber()), String.valueOf(list.get(position).getDept_id()), String.valueOf(list.get(position).getId()), list.get(position).getGname());
            }
        });
        ll_jinrugwc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TeChanActivity.this, GouWuCheActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
            }
        });
    }

    public void startXQ(Context context, String number, String dept_id, String id, String title) {
        Intent intent = new Intent(context, ProductDetailsActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("dept_id", dept_id);
        intent.putExtra("title", title);
        intent.putExtra("number", number);
        startActivity(intent);
    }

    @SuppressWarnings("unused")
    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题
        setTop(null, 0, getString(R.string.specialty), null, 0);
        setBackArrows(findViewById(R.id.top_bar_left_iv));

        id_swipe_ly_right = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly_right);
        goodgrid = (GridViewForScrollView) findViewById(R.id.goodgrid);
        circleTextView = (CircleTextView) findViewById(R.id.number);
        ll_jinrugwc = (LinearLayout) findViewById(R.id.ll_jinrugwc);

        sv = (ScrollView)findViewById(R.id.sv);

        sv.setOnTouchListener(new View.OnTouchListener() {
            private int lastY = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        lastY++;
                        break;
                    default:
                        break;
                }
                if (event.getAction() == MotionEvent.ACTION_UP && lastY > 0) {
                    lastY = 0;
                    View view = ((ScrollView) v).getChildAt(0);
                    if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) {
                        //加载数据代码
                        getGoodByType(false);
                    }
                }
                return false;
            }
        });
//        goodgrid.setOnLoaddingListener(new OnLoaddingListener() {
//            @Override
//            public void onLoadding() {
//                getGoodByType(false);
//            }
//        }, pagingHelp = new PagingHelp(this));

        /**
         * 广告条初始化
         */
        bannerAdAdapter = new BannerAdAdapter(this,
                (RelativeLayout) findViewById(R.id.swipe_banner), bannerAdDatas);

        baoKuanAdapter = new BaoKuanAdapter();
        goodgrid.setAdapter(baoKuanAdapter);

    }

    /**
     * 下拉刷新
     */

    private void shuaxin() {
        id_swipe_ly_right.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getGoodByType(true);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        upDataNumber();
    }

    class BaoKuanAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            final BaoKuanData itemData = (BaoKuanData) getItem(position);
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(TeChanActivity.this, R.layout.item_bao_kuan, null);
                viewHolder.grid_image = (ImageView) convertView.findViewById(R.id.grid_image);
                viewHolder.tv_gname = (TextView) convertView.findViewById(R.id.tv_gname);
                viewHolder.tv_gunit = (TextView) convertView.findViewById(R.id.tv_gunit);
                viewHolder.sell_price = (TextView) convertView.findViewById(R.id.sell_price);
                viewHolder.tv_oriprice = (TextView) convertView.findViewById(R.id.tv_oriprice);
                viewHolder.tv_lijigoumai = (TextView) convertView.findViewById(R.id.tv_lijigoumai);
                viewHolder.tv_buhuozhong = (TextView) convertView.findViewById(R.id.tv_buhuozhong);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 获取数据
            imageManager.bind(viewHolder.grid_image, HttpLocalUtils.getHttpFileUrl(list.get(position).getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_gname.setText(list.get(position).getGname());
            viewHolder.tv_gunit.setText(list.get(position).getPknum() + (list.get(position).getUnit() == null ? "" : "/" + list.get(position).getUnit()));
            viewHolder.sell_price.setText("¥" + list.get(position).getSell_price());
            viewHolder.tv_oriprice.setText("¥" + list.get(position).getOriginal_price());


            viewHolder.tv_lijigoumai.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (GwcDbUtil.addGoodAutoNumber(itemData.getDbGwcData())) {
                        if (GwcDbUtil.getGwcIdNumber(list.get(position).getId()) == list.get(position).getNumber()) {
                            viewHolder.tv_lijigoumai.setVisibility(View.GONE);
                            viewHolder.tv_buhuozhong.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });


            int ssss = (int)list.get(position).getNumber();
            if(ssss<=0){
                viewHolder.tv_lijigoumai.setVisibility(View.GONE);
                viewHolder.tv_buhuozhong.setVisibility(View.VISIBLE);
            }else{
                viewHolder.tv_lijigoumai.setVisibility(View.VISIBLE);
                viewHolder.tv_buhuozhong.setVisibility(View.GONE);
            }


            return convertView;
        }

        class ViewHolder {
            private ImageView grid_image;
            private TextView tv_gname;
            private TextView tv_gunit;
            private TextView sell_price;
            private TextView tv_oriprice;
            private TextView tv_lijigoumai;
            private TextView tv_buhuozhong;
        }

    }

    /**
     * 获取二级菜单数据
     */
    private void getGoodByType(final boolean isFist) {
        if (isFist) {
            pagingHelp.clear();
        }
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetGoodByType");
        httpRequestParams.addBodyParameter("seller_id", String.valueOf(MyApplication.shangjiaId));
        httpRequestParams.addBodyParameter("type", "3");
        httpRequestParams.addBodyParameter("pageindex", String.valueOf(pagingHelp.getPageindex()));
        httpRequestParams.addBodyParameter("Pagesize", String.valueOf(pagingHelp.getPageCount()));
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, null) {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    if (isFist) {
                        list.clear();
                    }
                    list.addAll(pagingHelp.getValidData(JsonHelper.parseCollection(jsonArray, ArrayList.class, BaoKuanData.class)));
//                    GwcDbUtil.setDataDbBKSelectNumber(list);
//                    goodgrid.loaddingFinsh();
                    baoKuanAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.setSwipeRefreshLayout(id_swipe_ly_right));
    }
    /**
     * 更新购物车的数量   少用
     */
    public void upDataNumber() {
        if (circleTextView != null) {
            upDataNumber(GwcDbUtil.getGwcAllNumber());
        }
    }

    /**
     * 更新购物车的数量
     */
    public void upDataNumber(int number) {
        if (circleTextView != null) {
            circleTextView.setNUmber(number);
        }
    }

    /**
     * 更新购物车的数量 加一
     */
    public void upDataNumberAdd() {
        if (circleTextView != null) {
            circleTextView.setNUmber(circleTextView.getNumber() + 1, true);
        }
    }

    /**
     * 更新购物车的数量 减一
     */
    public void upDataNumberSub() {
        if (circleTextView != null) {
            circleTextView.setNUmber(circleTextView.getNumber() - 1, true);
        }
    }
    /**
     获取首页轮播图片请求方法
     * */
    private void getBannerImage() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetHomePageImg");
        httpRequestParams.addBodyParameter("pageindex", "1");
        httpRequestParams.addBodyParameter("pagesize", "10");
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray array = json.getJSONArray("result");
                    for (int i = 0; i < array.length(); i++) {
                        BannerAdData bid = new BannerAdData();
                        bid.setContent_id(array.getJSONObject(i).getInt("content_id"));
                        bid.setContent_type(array.getJSONObject(i).getInt("content_type"));
                        bid.setImg_url(array.getJSONObject(i).getString("img_url"));
                        bannerAdDatas.add(bid);
                    }
                    bannerAdAdapter.notifyDataSetChanged();
                    bannerAdAdapter.start();

                    LogUtils.e("获取的url------->", "   " + bannerAdDatas.get(0).getImg_url());
                } catch (JSONException e) {

                }
            }
        });
    }
}
